package com.frxuexi.park2209.repair

import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.RepairBean
import com.frxuexi.base.entity.RepairBeanItem
import com.frxuexi.base.mvvm.BaseActivity
import com.frxuexi.base.net.Const
import com.frxuexi.park2209.R
import com.frxuexi.park2209.adapter.RepairAdapter
import com.frxuexi.park2209.databinding.ActivityRepairBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class RepairActivity : BaseActivity<ActivityRepairBinding, RepairViewModel>() {
    lateinit var repairAdapter: RepairAdapter
    var list = mutableListOf<RepairBeanItem>()
    var list3= mutableListOf<RepairBeanItem>()
    override fun initData() {
        lifecycleScope.launch {
            vm.allRepairs.collect {
                getData(it)
            }
        }

        lifecycleScope.launch {
            vm.myRepairs.collect {
                getData(it)
            }
        }

        lifecycleScope.launch {
            vm.appointRepair.collect {
                if (it.isNotEmpty()) {
                    ToastUtils.showLong("指定完成")
                    repairAdapter.data.clear()
                    list.clear()
                    vm.getAllRepairs()
                }
            }
        }
    }

    fun getData(it: String) {
        if (it.isNotEmpty()) {
            Log.i("===", it)
            val repairBean = Gson().fromJson(it, RepairBean::class.java)
            repairAdapter.apply {
                list.addAll(repairBean.filter { !it.repairData.isNullOrEmpty() && !it.repairDescribe.isNullOrEmpty() && it.repairData != "string" })
                addData(list.filter { it.repairUserId == 0 }.sortedByDescending { it.repairId }
                    .toMutableList())
                list3.addAll(list.filter { it.repairUserId == 0 }.sortedByDescending { it.repairId }
                    .toMutableList())
                notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
        binding.repHeader.ivBack.setOnClickListener {
            finish()
        }
        val uname = SPUtils.getInstance().getString(Const.UNAME, "")
        if (uname.contains("admin")) {
            vm.getAllRepairs()
            binding.repHeader.headerTv.apply {
                visibility = View.VISIBLE
                text = "管理"
                setOnClickListener {
                    repairAdapter.data.clear()
                    if (text == "管理") {
                        text = "完成"
                        binding.cbAll.visibility = View.VISIBLE
                        list3.forEach {
                            it.isShow = true
                        }
                    } else {
                        text = "管理"
                        binding.cbAll.visibility = View.GONE
                        list3=list3.filter { !it.isChecked }.toMutableList()
                        list3.forEach {
                            it.isShow = false
                        }
                        ToastUtils.showLong("操作完成")
                    }
                    repairAdapter.addData(list3)
                    repairAdapter.notifyDataSetChanged()
                }
            }

        } else {
            vm.getMyRepairs(mapOf("userId" to SPUtils.getInstance().getInt(Const.UID, -1)))
        }


        binding.cbAll.apply {
            setOnClickListener {
                var list3 = list.filter { it.repairUserId == 0 }
                list3.forEach {
                    it.isChecked=isChecked
                }
                repairAdapter.addData(list3)
                repairAdapter.notifyDataSetChanged()
            }
        }

        repairAdapter = RepairAdapter()
        binding.rvRepair.apply {
            adapter = repairAdapter
            layoutManager = LinearLayoutManager(this@RepairActivity)
        }

        repairAdapter.addChildClickViewIds(R.id.btn_approve,R.id.cb,R.id.repair_look)
        repairAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = repairAdapter.data.get(position)
            if(view.id==R.id.btn_approve) {
                if (uname.contains("admin") && item.repairUserId == 0) {
                    AlertDialog.Builder(this@RepairActivity)
                        .setTitle("指定维修人员")
                        .setMessage("王师傅")
                        .setNegativeButton("确定", object : OnClickListener {
                            override fun onClick(dialog: DialogInterface?, which: Int) {
//                            "repairId": 0,
//                            "repairTime": "string",
//                            "repairUserId": 0,
                                vm.appointRepair(
                                    mapOf(
                                        "repairId" to item.repairId,
                                        "repairUserId" to 455,
                                        "repairTime" to getDataTime(System.currentTimeMillis())
                                    )
                                )
                            }

                        }).show()
                }
            }else if(view.id==R.id.repair_look){
                val intent = Intent(this@RepairActivity, RepairDetailActivity::class.java)
                intent.putExtra("repair",item)
                startActivity(intent)
            }else{
                list3.get(position).isChecked=!list3.get(position).isChecked
                //全选的状态跟着item的checkbox状态改变
                if(list3.any {!it.isChecked}){//如果有任何一个未选中
                    binding.cbAll.isChecked=false
                }else {
                    binding.cbAll.isChecked = true
                }
                repairAdapter.notifyDataSetChanged()
            }
        }

        binding.tabRepair.apply {
            addTab(newTab().setText("未审核"))
            addTab(newTab().setText("已审核"))
            var list2 = mutableListOf<RepairBeanItem>()
            addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    repairAdapter.data.clear()
                    val position = tab?.position
                    if (position == 0) {
                        list2 = list.filter { it.repairUserId == 0 }.toMutableList()
                    } else {
                        list2 = list.filter { it.repairUserId > 0 }
                            .sortedByDescending { it.repairTime }.toMutableList()
                    }
                    repairAdapter.addData(list2)
                    repairAdapter.notifyDataSetChanged()

                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }

            })
        }
    }
}